﻿using System.Collections;
using UnityEngine;
using UniRx;

public class WalkMonsterFSM : FSMBase
{
    protected override string getName => "monster";

    private FSMStateStand standState = new FSMStateStand();
    private FSMStateAirborne airborneState = new FSMStateAirborne();
    private FSMStateStandSkill standSkillState = new FSMStateStandSkill();
    private FSMStateHurt hurtState = new FSMStateHurt();
    private FSMStateDie dieState = new FSMStateDie();


    private float m_HorizontalEasingAxis;

    protected override void InitParameters()
    {
        entity.controller.GetStream<float>("horizontal")
            .Subscribe(v => parameters.SetParam("horizontalAxis", v))
            .AddTo(entity);

        entity.controller.GetStream<int>("standSkill")
            .Subscribe(v => parameters.SetParam("standSkill", v))
            .AddTo(entity);

        entity.lifeCycle.GetLifeCycleStream(UnitLifeCycle.LifeType.FSMCondition).WhenActive(entity)
            .Subscribe(_ =>
            {
                parameters.SetParam("isGround", entity.physics.groundChecker.isGround);
                parameters.SetParam("isRising", entity.physics.velocity.y > 0);

                m_HorizontalEasingAxis = Mathf.MoveTowards(m_HorizontalEasingAxis, parameters.GetParam<float>("horizontalAxis"), Time.deltaTime / UnitDefine.BASE_ACCE_TIME);
                entity.animator.animator.SetFloat("horizontalAxis", m_HorizontalEasingAxis);
            })
            .AddTo(entity);
    }

    protected override void OnInit()
    {
        base.OnInit();

        RegisterState(standState, true);
        RegisterState(airborneState);
        RegisterState(standSkillState);
        RegisterState(hurtState);
        RegisterState(dieState);

        RegisterTransition(standState, airborneState, () => !parameters.GetParam<bool>("isGround"));
        RegisterTransition(airborneState, standState, () => parameters.GetParam<bool>("isGround") && !parameters.GetParam<bool>("isRising"));

        RegisterTransition(standState, standSkillState, entity.controller.GetStream<int>("standSkill").AsUnitObservable());
        RegisterTransition(standSkillState, standState);

        RegisterGlobalTransition(hurtState, condition: () => parameters.GetParam<float>("hurtAxis") != 0 && entity.attribute.currentHP > 0);
        RegisterTransition(hurtState, standState, () => parameters.GetParam<bool>("isGround"));
        RegisterTransition(hurtState, airborneState, () => !parameters.GetParam<bool>("isGround"));

        RegisterGlobalTransition(dieState, condition: () => parameters.GetParam<float>("hurtAxis") != 0 && entity.attribute.currentHP <= 0);
    }
}